<?php

define('TEMPLATE_WEUI', '../addons/dayu_comment/template/weui/');
defined('IN_IA') or exit('Access Denied');
class dayu_commentModuleSite extends WeModuleSite
{
	private $table_category = 'dayu_comment_category';
	private $tb_comment = 'dayu_comment';
	public $_appid = '';
	public $_appsecret = '';
	public $_accountlevel = '';
	public $_account = '';
	public $_weid = '';
	public $_openid = '';
	public $_nickname = '';
	public $_headimgurl = '';
	public $_auth2_openid = '';
	public $_auth2_nickname = '';
	public $_auth2_headimgurl = '';
	function __construct()
	{
		global $_W, $_GPC;
		load()->model('mc');
		$this->_openid = $_W['openid'];
		$this->_weid = $_W['uniacid'];
		$account = $_W['account'];
		$this->_auth2_openid = 'auth2_openid_' . $_W['uniacid'];
		$this->_auth2_nickname = 'auth2_nickname_' . $_W['uniacid'];
		$this->_auth2_headimgurl = 'auth2_headimgurl_' . $_W['uniacid'];
		$this->_appid = $_W['account']['key'];
		$this->_appsecret = $_W['account']['secret'];
		$this->_accountlevel = $account['level'];
		if (isset($_COOKIE[$this->_auth2_openid])) {
			$this->_openid = $_COOKIE[$this->_auth2_openid];
		}
		if ($this->_accountlevel < 4) {
			$settings = uni_setting($this->_weid);
			$oauth = $settings['oauth'];
			if (!empty($oauth) && !empty($oauth['account'])) {
				$this->_account = account_fetch($oauth['account']);
				$this->_appid = $this->_account['key'];
				$this->_appsecret = $this->_account['secret'];
			}
		} else {
			$this->_appid = $_W['account']['key'];
			$this->_appsecret = $_W['account']['secret'];
		}
	}
	public function oauth2($url)
	{
		global $_GPC, $_W;
		load()->func('communication');
		$code = $_GPC['code'];
		if (empty($code)) {
			$this->showMessage('code获取失败.');
		}
		$token = $this->get_Authorization_Code($code);
		$from_user = $token['openid'];
		$userinfo = $this->get_User_Info($from_user);
		$state = 1;
		if ($userinfo['subscribe'] == 0) {
			$state = 0;
			$authkey = intval($_GPC['authkey']);
			if ($authkey == 0) {
				$oauth2_code = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $this->_appid . "&redirect_uri=" . urlencode($url) . "&response_type=code&scope=snsapi_userinfo&state=0#wechat_redirect";
				header("location:$oauth2_code");
			}
			$userinfo = $this->get_User_Info($from_user, $token['access_token']);
		}
		if (empty($userinfo) || !is_array($userinfo) || empty($userinfo['openid']) || empty($userinfo['nickname'])) {
			echo '<h1>获取微信公众号授权失败[无法取得粉丝信息], 请稍后重试！ 公众平台返回原始数据: <br />' . $state . $userinfo['meta'] . '<h1>';
			exit;
		}
		setcookie($this->_auth2_headimgurl, $userinfo['headimgurl'], time() + 3600 * 24);
		setcookie($this->_auth2_nickname, $userinfo['nickname'], time() + 3600 * 24);
		setcookie($this->_auth2_openid, $from_user, time() + 3600 * 24);
		setcookie($this->_auth2_sex, $userinfo['sex'], time() + 3600 * 24);
		return $userinfo;
	}
	public function get_Access_Token()
	{
		global $_W;
		$account = $_W['account'];
		if ($this->_accountlevel < 4) {
			if (!empty($this->_account)) {
				$account = $this->_account;
			}
		}
		load()->classs('weixin.account');
		$accObj = WeixinAccount::create($account['acid']);
		$access_token = $accObj->fetch_token();
		return $access_token;
	}
	public function get_Authorization_Code($code)
	{
		$oauth2_code = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->_appid}&secret={$this->_appsecret}&code={$code}&grant_type=authorization_code";
		$error = ihttp_get($oauth2_code);
		$token = @json_decode($error['content'], true);
		if (empty($token) || !is_array($token) || empty($token['access_token']) || empty($token['openid'])) {
			$oauth2_code = $this->createMobileUrl('index', array(), true);
			header("location:$oauth2_code");
			echo '微信授权失败! 公众平台返回原始数据: <br>' . $error['meta'];
			exit;
		}
		return $token;
	}
	public function get_User_Info($from_user, $ACCESS_TOKEN = '')
	{
		if ($ACCESS_TOKEN == '') {
			$ACCESS_TOKEN = $this->get_Access_Token();
			$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$ACCESS_TOKEN}&openid={$from_user}&lang=zh_CN";
		} else {
			$url = "https://api.weixin.qq.com/sns/userinfo?access_token={$ACCESS_TOKEN}&openid={$from_user}&lang=zh_CN";
		}
		$json = ihttp_get($url);
		$userinfo = @json_decode($json['content'], true);
		return $userinfo;
	}
	public function get_Code($url)
	{
		global $_W;
		$url = urlencode($url);
		$oauth2_code = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->_appid}&redirect_uri={$url}&response_type=code&scope=snsapi_base&state=0#wechat_redirect";
		header("location:$oauth2_code");
	}
	public function doWebCategory()
	{
		global $_GPC, $_W;
		checklogin();
		$weid = $_W['uniacid'];
		$setting = $this->module['config'];
		$operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
		if ($operation == 'display') {
			$pindex = max(1, intval($_GPC['page']));
			$psize = 15;
			$category = pdo_fetchall("select * from " . tablename($this->table_category) . " where weid = :weid ORDER BY id DESC", array(':weid' => $weid));
			$total = pdo_fetchcolumn("SELECT count(id) FROM " . tablename($this->table_category) . " where weid = :weid ORDER BY id DESC", array(':weid' => $weid));
			$pager = pagination($total, $pindex, $psize);
			foreach ($category as $key => $val) {
				$category[$key]['a'] = $this->get_comment_total($val['id'], 1);
				$category[$key]['d'] = $this->get_comment_total($val['id'], 2);
			}
			include $this->template('category');
		} elseif ($operation == 'post') {
			$id = intval($_GPC['id']);
			if (!empty($id)) {
				$cate = pdo_get($this->table_category, array('weid' => $weid, 'id' => $id), array());
			}
			if (checksubmit('submit')) {
				if (empty($_GPC['title'])) {
					message('抱歉，请输入分类名称！');
				}
				$data = array('weid' => $weid, 'title' => $_GPC['title'], 'status' => $_GPC['status'], 'hide' => $_GPC['hide'], 'pic' => $_GPC['pic']);
				if (!empty($id)) {
					pdo_update($this->table_category, $data, array('id' => $id));
				} else {
					pdo_insert($this->table_category, $data);
					$id = pdo_insertid();
				}
				message('更新分类成功！', $this->createWebUrl('category', array('op' => 'display')), 'success');
			}
			include $this->template('category');
		} elseif ($operation == 'delete') {
			$id = intval($_GPC['id']);
			$category = pdo_fetch("SELECT * FROM " . tablename($this->table_category) . " WHERE id = '$id'");
			if (empty($category)) {
				message('抱歉，分类不存在或是已经被删除！', $this->createWebUrl('category', array('op' => 'display')), 'error');
			}
			pdo_delete($this->table_category, array('id' => $id));
			message('分类删除成功！', $this->createWebUrl('category', array('op' => 'display')), 'success');
		}
	}
	public function doWebComment()
	{
		global $_W, $_GPC;
		checklogin();
		$weid = $_W['uniacid'];
		$setting = $this->module['config'];
		$cid = $_GPC['cid'];
		$op = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
		$category = pdo_fetch("SELECT * FROM " . tablename($this->table_category) . " WHERE id = :id", array(":id" => $cid));
		$pindex = max(1, intval($_GPC['page']));
		$psize = 10;
		$where .= 'weid=:weid and cid=:cid and rid=0';
		if (!empty($_GPC['keywords'])) {
			$where .= " AND content LIKE '%{$_GPC['keywords']}%'";
		}
		if (!empty($_GPC['id'])) {
			$where .= " AND id=" . $_GPC['id'];
		}
		if (!empty($_GPC['recycle'])) {
			$where .= " AND recycle = 1";
		} else {
			$where .= " AND recycle = 0";
		}
		if ($op == 'display') {
			$comments = pdo_fetchall("SELECT * FROM " . tablename($this->tb_comment) . " WHERE {$where} ORDER BY createtime DESC,id DESC LIMIT " . ($pindex - 1) * $psize . ",{$psize}", array(':weid' => $weid, ':cid' => $cid), 'id');
			$total = pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename($this->tb_comment) . " WHERE {$where}", array(':weid' => $weid, ':cid' => $cid));
			$pager = pagination($total, $pindex, $psize);
			foreach ($comments as $key => $val) {
				$comments[$key]['user'] = mc_fansinfo($val['openid'], $acid, $weid);
				$comments[$key]['createtime'] = date("Y-m-d H:i:s", $val['createtime']);
				$comments[$key]['thumb'] = iunserializer($val['thumb']);
			}
			$boss = array();
			$commentid = array_keys($comments);
			$childlist = pdo_fetchall("SELECT * FROM " . tablename($this->tb_comment) . " WHERE rid IN ('" . implode("','", is_array($commentid) ? $commentid : array($commentid)) . "') AND rid!=0 AND weid=:weid and cid=:cid ORDER BY createtime DESC,id DESC", array(':weid' => $weid, ':cid' => $cid));
			foreach ($childlist as $index => $row) {
				array_unshift($boss, $row['uid']);
				if (!empty($row['rid'])) {
					$children[$row['rid']][] = $row;
				}
			}
			$avatar = !empty($boss) ? mc_fansinfo($row['openid'], $acid, $weid) : "resource/images/noavatar_middle.gif";
		}
		include $this->template('comment');
	}
	public function doWebCustomDelete()
	{
		global $_W, $_GPC;
		checklogin();
		$weid = $_W['uniacid'];
		$id = intval($_GPC['id']);
		$table = $_GPC['table'];
		if (!empty($id)) {
			pdo_delete($table, array('id' => $id));
		}
		message('删除成功.', referer());
	}
	public function doWebAjaxSet()
	{
		global $_GPC, $_W;
		checklogin();
		$weid = $_W['uniacid'];
		$id = intval($_GPC['id']);
		$type = $_GPC['type'];
		$data = intval($_GPC['data']);
		$table = $_GPC['table'];
		if (in_array($type, array('status', 'recycle', 'hide', 'pic'))) {
			$data = $data == 1 ? '0' : '1';
			pdo_update($table, array($type => $data), array("id" => $id, "weid" => $weid));
			die(json_encode(array("result" => 1, "data" => $data)));
		}
		die(json_encode(array("result" => 0)));
	}
	public function get_comment_total($cid, $type)
	{
		global $_GPC, $_W;
		if ($type == '1') {
			return pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename($this->tb_comment) . " WHERE weid = :weid AND cid = :cid", array(":weid" => $_W['uniacid'], ":cid" => $cid));
		} elseif ($type == '2') {
			return pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename($this->tb_comment) . " WHERE weid = :weid AND cid = :cid AND recycle=1", array(":weid" => $_W['uniacid'], ":cid" => $cid));
		}
	}
	public function doMobileGetContent()
	{
		global $_W, $_GPC;
		$reid = intval($_GPC['reid']);
		$comment = pdo_get('dayu_comment', array('weid' => $_W['uniacid'], 'id' => $_GPC['id']), array());
		$createtime = date('Y-m-d H:i', $comment['createtime']);
		$html = '
			<ul class="weui-comment bg-white">
				<li class="weui-comment-item"> 
					<div class="weui-comment-li">
						<small class="check checked">' . $createtime . '</small>
					</div>
					<div class="userinfo">
						<span class="ico_scored block"><strong class="score_' . $comment['score'] . '"></strong></span>
						<img class="avatar" src="' . TEMPLATE_WEUI . '/images/talk.png">
					</div>
					<div class="weui-comment-msg">
					
					</div>
					<p class="time">
						' . $comment['content'] . '
					</p>
				</li>
			</ul>
		';
		if (empty($comment)) {
			$result['status'] = 0;
			$result['msg'] = $_GPC['id'] . ' 评论不存在';
		} else {
			$result['status'] = 1;
			$result['msg'] = $html;
		}
		message($result, '', 'ajax');
	}
	public function doMobileAjaxGet()
	{
		global $_W, $_GPC;
		$weid = intval($_GPC['weid']);
		$cid = intval($_GPC['cid']);
		$reid = intval($_GPC['reid']);
		$infoid = intval($_GPC['infoid']);
		$addons = trim($_GPC['addons']);
		$cate = pdo_get($this->table_category, array('weid' => $weid, 'id' => $cid), array());
		$html .= '<div class="weui_cell_bd weui_cell_primary">
				<div class="weui_uploader">
					<div class="weui_uploader_hd weui_cell">
						<div class="weui_cell_bd weui_cell_primary">上传图片</div>
						<div class="weui_cell_ft"></div>
					</div>
					<div class="weui_uploader_bd">
						<ul class="weui_uploader_files" id="pub-pics">   
						</ul>
						<div class="weui_uploader_input_wrp">
							<div id="chooseImage" style="width: 100%;height: 100%;" class="weui_uploader_input"></div> 
						</div>
					</div>
				</div>
			</div>';
		$result['state'] = 0;
		$result['hide'] = $cate['hide'];
		$result['hidehtml'] = '<div class="weui_cell_hd weui_cell_primary"><small>隐藏昵称</small></div><div class="weui_cell_ft"><input class="weui_switch" id="hid" name="hid" type="checkbox" value="1"></div>';
		$result['pic'] = $cate['pic'];
		$result['pichtml'] = $html;
		$result['status'] = $cate['status'];
		message($result, '', 'ajax');
	}
	public function doMobileAjaxPost()
	{
		global $_W, $_GPC;
		$weid = intval($_GPC['weid']);
		$uid = intval($_GPC['uid']);
		$openid = $_GPC['openid'];
		$cid = intval($_GPC['cid']);
		$reid = intval($_GPC['reid']);
		$infoid = intval($_GPC['infoid']);
		$hid = intval($_GPC['hid']);
		$addons = trim($_GPC['addons']);
		$thumbs = explode(',', rtrim($_GPC['thumb'], ","));
		$check = pdo_get($this->tb_comment, array('weid' => $weid, 'cid' => $cid, 'reid' => $reid, 'infoid' => $infoid, 'addons' => $addons, 'openid' => $openid), array());
		if (empty($cid) || empty($reid) || empty($infoid) || empty($addons) || empty($_GPC['score']) || empty($_GPC['content'])) {
			$result['status'] = 0;
			$result['msg'] = $cid . '系统发生错误';
		} else {
			$data = array('weid' => $weid, 'cid' => $cid, 'reid' => $reid, 'infoid' => $infoid, 'uid' => $uid, 'openid' => $openid, 'hide' => $hid, 'content' => trim($_GPC['content']), 'score' => intval($_GPC['score']), 'addons' => $addons, 'createtime' => TIMESTAMP);
			if (!empty($_GPC['thumb']) && is_array($thumbs)) {
				foreach ($thumbs as $thumb) {
					$th[] = tomedia($thumb);
				}
				$data['thumb'] = iserializer($th);
			}
			if (pdo_insert($this->tb_comment, $data) === false) {
				$result['status'] = 0;
				$result['msg'] = '发布评论失败';
			} else {
				$table = $addons;
				$table_info = $addons . '_info';
				$commentid = pdo_insertid();
				$updata = array('commentid' => $commentid);
				pdo_update($table_info, $updata, array('reid' => $reid, 'rerid' => $infoid));
				$primary = pdo_get($table, array('weid' => $weid, 'reid' => $reid), array());
				pdo_update($table, array('score_total' => intval($primary['score_total']) + intval($_GPC['score']), 'score_num' => intval($primary['score_num']) + 1), array('reid' => $reid));
				$result['status'] = 1;
				$result['time'] = date('Y-m-d H:i:s', $data['createtime']);
				$result['css'] = 'score_' . $data['score'];
				$result['content'] = $data['content'];
				$result['msg'] = '发布评论成功';
			}
		}
		message($result, '', 'ajax');
	}
	public function doMobileGetComment()
	{
		global $_GPC, $_W;
		$reid = intval($_GPC['reid']);
		$pindex = isset($_REQUEST['page']) ? max(1, $_REQUEST['page']) : '';
		$psize = 10;
		$where = 'weid=:weid AND reid = :reid and rid=0 and recycle=0';
		$params = array();
		$params[':weid'] = $_W['uniacid'];
		$params[':reid'] = $reid;
		$sql = 'SELECT * FROM ' . tablename($this->tb_comment) . " WHERE $where order by createtime DESC LIMIT " . ($pindex - 1) * $psize . ',' . $psize;
		$comments = pdo_fetchall($sql, $params, 'id');
		$data = array();
		foreach ($comments as $key => $value) {
			$childlist = pdo_fetchall("SELECT * FROM " . tablename($this->tb_comment) . " WHERE rid = :rid AND weid=:weid ORDER BY createtime DESC,id DESC", array(':weid' => $_W['uniacid'], ':rid' => $value['id']));
			$comments[$key]['user'] = mc_fansinfo($value['openid']);
			$comments[$key]['nickname'] = $value['hide'] == 1 ? "***(匿名)" : $comments[$key]['user']['nickname'];
			$comments[$key]['avatar'] = $value['hide'] == 1 ? TEMPLATE_WEUI . "images/noface.jpg" : $comments[$key]['user']['tag']['avatar'];
			$comments[$key]['createtime'] = date("Y-m-d", $value['createtime']);
			$comments[$key]['thumb'] = iunserializer($value['thumb']);
			$thumb = '';
			if (is_array($comments[$key]['thumb'])) {
				foreach ($comments[$key]['thumb'] as $pic) {
					$thumb .= '<div class="thumbnail" onclick="commentsshow(this)" data="' . $pic . '"><img src="' . $pic . '"></div>';
				}
			}
			foreach ($childlist as $fd) {
				$comments[$key]['isre'][$fd['rid']] = $fd['content'];
				$comments[$key]['isre'][$fd['time']] = date("Y-m-d", $fd['createtime']);
				$comments[$key]['reply'][$fd['rid']] = '<p class="liketext f12 lheight"><svg class="icon f18" aria-hidden="true"><use xlink:href="#icon-staff"></use></svg> ' . $fd['content'] . ' <small class="f-gray right">' . date("Y-m-d", $fd['createtime']) . '</small></p>';
			}
			$data[] = array('id' => $value['id'], 'avatar' => $comments[$key]['avatar'], 'nickname' => $comments[$key]['nickname'], 'content' => $comments[$key]['content'], 'contents' => !empty($comments[$key]['isre'][$fd['rid']]) ? $comments[$key]['reply'][$fd['rid']] : '', 'score' => $comments[$key]['score'], 'thumb' => $thumb, 'time' => $comments[$key]['createtime']);
		}
		return json_encode($data);
	}
	public function doMobileAvatar()
	{
		global $_W, $_GPC;
		require 'fans.mobile.php';
		$setting = $this->module['config'];
		$jquery = 2;
		include $this->template('avatar');
	}
	public function send_template_message($data)
	{
		global $_W, $_GPC;
		$atype = 'weixin';
		$account_code = "account_weixin_code";
		load()->classs('weixin.account');
		$access_token = WeAccount::token();
		$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
		$response = ihttp_request($url, $data);
		if (is_error($response)) {
			return error(-1, "访问公众平台接口失败, 错误: {$response['message']}");
		}
		$result = @json_decode($response['content'], true);
		if (empty($result)) {
			return error(-1, "接口调用失败, 元数据: {$response['meta']}");
		} elseif (!empty($result['errcode'])) {
			return error(-1, "访问微信接口错误, 错误代码: {$result['errcode']}, 错误信息: {$result['errmsg']}");
		}
		return true;
	}
	public function AjaxMessage($msg, $status = 0)
	{
		$result = array('message' => $msg, 'status' => $status);
		echo json_encode($result);
		exit;
	}
	public function get_userinfo($weid, $openid)
	{
		load()->model('mc');
		return mc_fetch($openid);
	}
	public function get_info($uid)
	{
		global $_W;
		return pdo_fetch("SELECT * FROM " . tablename('mc_members') . " WHERE uniacid = :uniacid AND uid = :uid", array(':uniacid' => $_W['uniacid'], ':uid' => $uid));
	}
	public function isHy($openid)
	{
		global $_W;
		load()->model('mc');
		$card = pdo_fetch("SELECT * FROM " . tablename("mc_card_members") . " WHERE uniacid=:uniacid AND openid = :openid ", array(':uniacid' => $_W['uniacid'], ':openid' => $openid));
		if (empty($card)) {
			return false;
		} else {
			return true;
		}
	}
	public function doMobileFansUs()
	{
		global $_W, $_GPC;
		$qrcodesrc = tomedia('qrcode_' . $_W['acid'] . '.jpg');
		include $this->template('fans_us');
	}
	public function getFollow()
	{
		global $_GPC, $_W;
		$p = pdo_fetch("SELECT follow FROM " . tablename('mc_mapping_fans') . " WHERE uniacid = :weid AND openid = :openid LIMIT 1", array(":weid" => $_W['uniacid'], ":openid" => $_W['openid']));
		if (intval($p['follow']) == 0) {
			header('Location: ' . $this->createMobileUrl('FansUs'), true, 301);
		} else {
			return true;
		}
	}
	public function showMessage($msg, $redirect = '', $type = '')
	{
		global $_W;
		if ($redirect == 'refresh') {
			$redirect = $_W['script_name'] . '?' . $_SERVER['QUERY_STRING'];
		} elseif (!empty($redirect) && !strexists($redirect, 'http://')) {
			$urls = parse_url($redirect);
			$redirect = $_W['siteroot'] . 'app/index.php?' . $urls['query'];
		}
		if ($redirect == '') {
			$type = in_array($type, array('success', 'error', 'info', 'warning', 'ajax', 'sql')) ? $type : 'info';
		} else {
			$type = in_array($type, array('success', 'error', 'info', 'warning', 'ajax', 'sql')) ? $type : 'success';
		}
		if ($_W['isajax'] || $type == 'ajax') {
			$vars = array();
			$vars['message'] = $msg;
			$vars['redirect'] = $redirect;
			$vars['type'] = $type;
			exit(json_encode($vars));
		}
		if (empty($msg) && !empty($redirect)) {
			header('location: ' . $redirect);
		}
		$label = $type;
		if ($type == 'error') {
			$label = 'danger';
			$info = '出错了，原因：';
		}
		if ($type == 'ajax' || $type == 'sql') {
			$label = 'warning';
			$info = '访问受限，原因：';
		}
		if ($type == 'info') {
			$label = 'info';
			$info = '提示';
		}
		if ($type == 'success') {
			$info = '操作成功';
		}
		if (defined('IN_API')) {
			exit($msg);
		}
		include $this->template('messages', TEMPLATE_INCLUDEPATH);
		exit;
	}
}